package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Service
@Slf4j   //日志处理
public class AuthFilter implements GlobalFilter, Ordered {

    /**
     * 过滤器执行的逻辑
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //从请求对象中获取请路径
        String path = request.getURI().getPath();
        //判断请求地址是否需要授权
        //直接判断地址中是否包含  "/login"
        if (path.contains("/login")) {
            //如果包含直接放行
            return chain.filter(exchange);
        }

        //从请求对象中获取请求头
        String token = request.getHeaders().getFirst("token");
        //不包含，需要鉴权，需要判断请求头中是否携带token
        //没有，返回401为授权
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //直接响应给客户，不再往后端的请求转发
            return response.setComplete();
        }
        //有token，验证token是否有效
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int result = AppJwtUtil.verifyToken(claimsBody);
            //无效，返回401，未授权
            //有效，从token中提取用户id
            if (result == -1 || result == 0) {
                Object userId = claimsBody.get("userId");
                // 将用户id放回到请求头中,然后将带有用户id的请求转发给后端的微服务,放行请求
                request.mutate().header("userId",userId.toString());
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        //设置返回状态
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //直接响应给客户端,不再往后端的请求转发
        return response.setComplete();
    }


    /**
     * 过滤器执行的顺序 数值越小,优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}




















